package com.xmh.security_1.controller;

import com.xmh.security_1.entity.UserEntity;
import com.xmh.security_1.vo.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/login")
@Transactional
@CrossOrigin
public class LoginRegController {

    @Autowired
    private SessionRegistry sessionRegistry;

    /**
     * 如果自动跳转到这个页面，说明用户未登录，返回相应的提示即可
     * <p>
     * 如果要支持表单登录，可以在这个方法中判断请求的类型，进而决定返回JSON还是HTML页面
     *
     * @return
     */
    @RequestMapping("/page")
    @ResponseBody
    public String loginPage() {
        return "error,这里是登录页面！尚未登录，请登录!";
    }

    @RequestMapping("/invalid")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public String invalid() {
        return "Session 已过期，请重新登录";
    }

    @PostMapping("/click")
    @ResponseBody
    public Result removeUserSessionByUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            return new Result(500, "字段缺失！");
        }

        int count = 0;
        //获取所有 principal 信息
        List<Object> users = sessionRegistry.getAllPrincipals();
        for (Object user : users) {
            if (user instanceof UserEntity) {
//              通过 principal.getUsername 是否等于输入值，获取到指定用户的 principal
                String principalName = ((UserEntity) user).getUsername();
                if (principalName.equals(username)) {
//                  sessionRegistry.getAllSessions(principal, false)获取该 principal 上的所有 session
                    List<SessionInformation> allSessions = sessionRegistry.getAllSessions(user, false);
                    if (allSessions != null && allSessions.size() > 0) {
//                        allSessions.forEach(SessionInformation::expireNow);
                        for (SessionInformation sessionInformation : allSessions) {
//                          通过 sessionInformation.expireNow() 使得 session 过期
                            sessionInformation.expireNow();
                            count++;
                        }
                    }
                }
            }
        }
        return new Result(200, "操作成功，清理session共" + count + "个");
    }


}
